#!/usr/bin/env python
# -*- coding:utf-8 -*-

from db.dbConn import DBConn
from logger import logger


class MySQLBase(object):
    """MySQL数据库类
    输入：数据源，SQL语句
    """

    def __init__(self):
        """Init MySQLBase
        """
        self.sql = """show databases;"""
        self.datasouce = ''

    def query(self, datasouce, sqlmodle):
        """查询MySQL数据 insert、update、delete返回None"""
        self.datasouce = datasouce
        self.sql = sqlmodle
        try:
            conn, cursor = DBConn(**self.datasouce).mysql_conn()
            cursor.execute(self.sql)
            res = cursor.fetchall()
            conn.commit()
            cursor.close()
            conn.close()
            return res
        except Exception as e:
            logger.error("SQL执行失败，执行语句为：{}".format(self.sql))
            logger.error(e)
            return 0


class InfluxBase(object):
    """数据库查询类
    输入：数据源，SQL语句
    """

    def __init__(self, datasouce):
        """Init InfluxBase
        """
        self.datasouce = datasouce
        self.sql = ''

    def query(self, sqlmodle):
        """查询Influxdb数据"""
        self.sql = sqlmodle
        try:
            client = DBConn(**self.datasouce).influx_conn()
            result = client.query(self.sql)
            return result
        except Exception as e:
            logger.error("influx 连接失败，请稍后重试。")
            logger.error(e)
            return 0

    def insert(self, points):
        """插入Influxdb数据
           points: JSON串
        """
        try:
            client = DBConn(**self.datasouce).influx_conn()
            client.write_points(points=points, time_precision='s', batch_size=None)
            return 1
        except Exception as e:
            logger.error("influx 写入失败，请查看。")
            logger.error(e)
            return 0

